$(document).ready(function () {
    // 定义域名变量
    var domain;
    // 判断当前环境
    if (window.location.href.indexOf('localhost') !== -1 || window.location.href.indexOf('127.0.0.1') !== -1) {
        // 本地开发环境
        domain = "http://127.0.0.1:5500";
    } else {
        // 线上环境
        domain = "http://mainbao.gitee.io/pianosystem1";
    }

    //是否开启计算
    var isCompute = false;

    //记录音程音符数组
    var intervalList = [];
    // 定义音程类型数组
    var intervals = ["", "小二度", "大二度", "小三度", "大三度", "纯四度", "增四度", "纯五度", '小六度', '大六度', '小七度', '大七度', '八度', '1个八度+小二度', '1个八度+大二度'];



    var functionKeys = [
        { key: "Esc", code: "27" },
        { key: "F1", code: "112" },
        { key: "F2", code: "113" },
        { key: "F3", code: "114" },
        { key: "F4", code: "115" },
        { key: "F5", code: "116" },
        { key: "F6", code: "117" },
        { key: "F7", code: "118" },
        { key: "F8", code: "119" },
        { key: "F9", code: "120" },
        { key: "F10", code: "121" },
        { key: "F11", code: "122" },
        { key: "F12", code: "123" }
    ];

    var mainKeyboard = [
        { key: "`", code: "192" }, { key: "1", code: "49" }, { key: "2", code: "50" }, { key: "3", code: "51" }, { key: "4", code: "52" }, { key: "5", code: "53" }, { key: "6", code: "54" }, { key: "7", code: "55" }, { key: "8", code: "56" }, { key: "9", code: "57" }, { key: "0", code: "48" }, { key: "-", code: "189" }, { key: "+", code: "187" }, { key: "back", code: "8" },
        { key: "Tab", code: "9" }, { key: "Q", code: "81", pianoKey: '51' }, { key: "W", code: "87", pianoKey: '53' }, { key: "E", code: "69", pianoKey: '55' }, { key: "R", code: "82", pianoKey: '56' }, { key: "T", code: "84", pianoKey: '58' }, { key: "Y", code: "89", pianoKey: '60' }, { key: "U", code: "85", pianoKey: '62' }, { key: "I", code: "73" }, { key: "O", code: "79" }, { key: "P", code: "80" }, { key: "{", code: "219" }, { key: "}", code: "221" }, { key: "\\", code: "220" },
        { key: "Lock", code: "20" }, { key: "A", code: "65", pianoKey: '39' }, { key: "S", code: "83", pianoKey: '41' }, { key: "D", code: "68", pianoKey: '43' }, { key: "F", code: "70", pianoKey: '44' }, { key: "G", code: "71", pianoKey: '46' }, { key: "H", code: "72", pianoKey: '48' }, { key: "J", code: "74", pianoKey: '50' }, { key: "K", code: "75" }, { key: "L", code: "76" }, { key: ";", code: "186" }, { key: "“", code: "222" }, { key: "Enter", code: "13", colspan2: true },
        { key: "Shift", code: "16", colspan2: true }, { key: "Z", code: "90", pianoKey: '27' }, { key: "X", code: "88", pianoKey: '29' }, { key: "C", code: "67", pianoKey: '31' }, { key: "V", code: "86", pianoKey: '32' }, { key: "B", code: "66", pianoKey: '34' }, { key: "N", code: "78", pianoKey: '36' }, { key: "M", code: "77", pianoKey: '38' }, { key: "<", code: "188" }, { key: ">", code: "190" }, { key: "?", code: "191" }, { key: "Shift", code: "16", colspan2: true },
        { key: "Ctrl", code: "17" }, { key: "win", code: "91" }, { key: "alt", code: "18" }, { key: "blank", code: "32", colspan9: true }, { key: "alt", code: "18" }, { key: "Ctrl", code: "17" },
    ];

    var numpad = [
        { key: "Num", code: "144" }, { key: "/", code: "111" }, { key: "*", code: "106" }, { key: "-", code: "109" },
        { key: "7", code: "103" }, { key: "8", code: "104" }, { key: "9", code: "105" }, { key: "+", code: "107", rowspan2: true },
        { key: "4", code: "100" }, { key: "5", code: "101" }, { key: "6", code: "102" },
        { key: "1", code: "97" }, { key: "2", code: "98" }, { key: "3", code: "99" }, { key: "Enter", code: "13", rowspan2: true }, { key: "0", code: "96" },
        { key: ".", code: "110" },
    ];

    var audioContext = new (window.AudioContext || window.webkitAudioContext)();
    var tracks = [];
    var activeDivs = [];
    var audioMap = {}; // 存储按键码和对应的音轨
    var activeDivs = []; // 存储当前高亮的div索引

    $(".interval-btn-start").click(function () {
        $(this).attr("disabled", "disabled");
        $("#select-tuning").attr("disabled", "disabled");
        // $(this).css("background", "red");
        $(".interval-tips").css("display", "inline-block");
        isCompute = true
        $(".piano-key").removeClass('highlighted')
    })

    $(".interval-btn-reset").click(function () {
        isCompute = true
        $(".interval-list").html('')
        intervalList = []
        $(".interval-btn-start").attr("disabled", false);
        $(".interval-btn-start").css("background", "red");
        $(".piano-key").removeClass('highlighted')
    })

    $(".interval-btn-stop").click(function () {
        $(".interval-btn-start").css("background", "red");
        $(".interval-tips").css("display", "none");
        $(".interval-btn-start").attr("disabled", false);
        $("#select-tuning").attr("disabled", false);
        isCompute = false;
        $(".interval-list").html('')
        intervalList = []
        $(".piano-key").removeClass('highlighted')
    })

    $(".show-btn").click(function () {
        $.fn.msg({
            content: '正在开发中！',
            type: 'error'
        });
    })

    //降
    $(".drop-btn").click(function () {
        $(".piano-key").removeClass('highlighted')
        if ($(".interval-sound").length == 0) {
            $.fn.msg({
                content: '点击开始计算按钮后，点击钢琴键盘!',
                type: 'error'
            });
        } else {
            for (var i = 0; i < intervalList.length; i++) {
                let index = intervalList[i];
                let num = pianoKeys.indexOf(index) - 1
                intervalList[i] = pianoKeys[num];
                $(".piano-key").eq(num).addClass('highlighted')
            }
            updateIntervalList(intervalList)
        }
    })
    //升
    $(".liter-btn").click(function () {
        $(".piano-key").removeClass('highlighted')
        if ($(".interval-sound").length == 0) {
            $.fn.msg({
                content: '点击开始计算按钮后，点击钢琴键盘!',
                type: 'error'
            });
        } else {
            for (var i = 0; i < intervalList.length; i++) {
                let index = intervalList[i];
                let num = pianoKeys.indexOf(index) + 1
                intervalList[i] = pianoKeys[num];
                $(".piano-key").eq(num).addClass('highlighted')
            }
            updateIntervalList(intervalList)
        }
    })


    //当前的调
    const currentScale = "C 调";
    //高亮当前的中央C键
    //预加载88个mp3，文件命名是从0开始到87
    // for (var i = 0; i < 87; i++) {
    //     var audio = new Audio(domain + "/mp3/" + i + ".mp3");
    //     audio.load();
    // }


    const pianoKeys = [
        'A0', 'A#0/Bb0', 'B0',
        'C1', 'C#1/Db1', 'D1', 'D#1/Eb1', 'E1', 'F1', 'F#1/Gb1', 'G1', 'G#1/Ab1',
        'A1', 'A#1/Bb1', 'B1',
        'C2', 'C#2/Db2', 'D2', 'D#2/Eb2', 'E2', 'F2', 'F#2/Gb2', 'G2', 'G#2/Ab2',
        'A2', 'A#2/Bb2', 'B2',
        'C3', 'C#3/Db3', 'D3', 'D#3/Eb3', 'E3', 'F3', 'F#3/Gb3', 'G3', 'G#3/Ab3',
        'A3', 'A#3/Bb3', 'B3',
        'C4', 'C#4/Db4', 'D4', 'D#4/Eb4', 'E4', 'F4', 'F#4/Gb4', 'G4', 'G#4/Ab4',
        'A4', 'A#4/Bb4', 'B4',
        'C5', 'C#5/Db5', 'D5', 'D#5/Eb5', 'E5', 'F5', 'F#5/Gb5', 'G5', 'G#5/Ab5',
        'A5', 'A#5/Bb5', 'B5',
        'C6', 'C#6/Db6', 'D6', 'D#6/Eb6', 'E6', 'F6', 'F#6/Gb6', 'G6', 'G#6/Ab6',
        'A6', 'A#6/Bb6', 'B6',
        'C7', 'C#7/Db7', 'D7', 'D#7/Eb7', 'E7', 'F7', 'F#7/Gb7', 'G7', 'G#7/Ab7',
        'A7', 'A#7/Bb7', 'B7',
        'C8'
    ];

    const songName = "修炼爱情"; // 添加歌曲名字
    //歌词对应和弦的配置，newLine是否换行
    const songData = [
        { chord: "F", lyrics: "的心酸", newLine: true },
        { chord: "G", lyrics: "学会放好", newLine: true },
        { chord: "Em", lyrics: "以前的渴", newLine: true },
        { chord: "Am", lyrics: "望我们", newLine: true },
        { chord: "Dm", lyrics: "那些信仰", newLine: true },
        { chord: "G", lyrics: "要忘记多", newLine: true },
        { chord: "C", lyrics: "难", newLine: true },
    ];

    // 12个调式
    const scales = {
        'C 调': ['C4', 'D4', 'E4', 'F4', 'G4', 'A4', 'B4', 'C5'],
        '#C 调': ['C#4/Db4', 'D#4/Eb4', 'F4', 'F#4/Gb4', 'G#4/Ab4', 'A#4/Bb4', 'C5','C#5/Db5'],
        'D 调': ['D4', 'E4', 'F#4/Gb4', 'G4', 'A4', 'B4', 'C#5/Db5','D5'],
        '#D 调': ['D#4/Eb4', 'F4', 'G4', 'G#4/Ab4', 'A#4/Bb4', 'C5', 'D5','D#5/Eb5'],
        'E 调': ['E4', 'F#4/Gb4', 'G#4/Ab4', 'A4', 'B4', 'C#5/Db5', 'D#5/Eb5','E5'],
        'F 调': ['F4', 'G4', 'A4', 'A#4/Bb4', 'C5', 'D5', 'E5','F5'],
        '#F 调': ['F#4/Gb4', 'G#4/Ab4', 'A#4/Bb4', 'B4', 'C#5/Db5', 'D#5/Eb5','F5','F#5/Gb5'],
        'G 调': ['G4', 'A4', 'B4', 'C5', 'D5', 'E5', 'F#5/Gb5','G5'],
        '#G 调': ['G#4/Ab4', 'A#4/Bb4', 'C5', 'C#5/Db5', 'D#5/Eb5', 'F5', 'G5','G#5/Ab5'],
        'A 调': ['A4', 'B4', 'C#5/Db5', 'D5', 'E5', 'F#5/Gb5', 'G#5/Ab5','A5'],
        '#A 调': ['A#4/Bb4', 'C5', 'D5', 'D#5/Eb5', 'F5', 'G5', 'A5','A#5/Bb5'],
        'B 调': ['B4', 'C#5/Db5', 'D#5/Eb5', 'E5', 'F#5/Gb5', 'G#5/Ab5', 'A#5/Bb5','B5'],
    };

    // C调下和弦标准
    const chords = {
        'C': ['C4', 'E4', 'G4'],
        'Cm': ['C4', 'D#4/Eb4', 'G4'],
        'D': ['D4', 'F#4/Gb4', 'A4'],
        'Dm': ['D4', 'F4', 'A4'],
        'E': ['E4', 'G#4/Ab4', 'B4'],
        'Em': ['E4', 'G4', 'B4'],
        'F': ['F4', 'A4', 'C5'],
        'Fm': ['F4', 'G#4/Ab4', 'C5'],
        'G': ['G4', 'B4', 'D5'],
        'Gm': ['G4', 'A#4/Bb4', 'D5'],
        'A': ['A4', 'C#5/Db5', 'E5'],
        'Am': ['A4', 'C5', 'E5'],
    }

    for (let key in scales) {
        const option = $('<option></option>').attr('value', key).text(key);
        const li  = $('<li></li>').attr('value', key).text(key);
        $('#select-tuning').append(option);
        $('.select-tuning').append(li);
    }
    for (let key in chords) {
        const option = $('<option></option>').attr('value', key).text(key);
        $('#select-chord').append(option);
    }

    //调式下拉菜单
    $('.select-tuning li').click(function(){
        $('.select-tuning li').removeClass('active')
        $(this).addClass('active')
        highlightPianoKeysForScale($(this).attr('value'));
        $('#select-tuning').val($(this).attr('value'))
    })

    $('#select-tuning').change(function () {
        highlightPianoKeysForScale($(this).val());
        $('#select-chord').val('')
    });

    $('#select-chord').change(function () {
        var selectedIndex = $('#select-tuning option:selected').index(); //调
        
        highlightPianoKeys($(this).val(),selectedIndex);
        //获取当前和弦详情的函数
        getChordDetail($(this).val());
    });

    function getChordDetail(chordName) {
        //获取当前和弦详情的函数
        $(".chord-info .chord-name span").text(chordName);
    }

    //是否显示简谱名
    $("#show-name").change(function () {
        if ($(this).prop("checked")) {
            $(".piano-key span").show()
        } else {
            $(".piano-key span").hide();
        }
    });

    $("#show-keyboard").change(function () {
        if ($(this).prop("checked")) {
            $(".keyboard-map").css('visibility', 'initial')
        } else {
            $(".keyboard-map").css('visibility', 'hidden');
        }
    });

    $("#switch-interval").change(function () {
        if ($(this).prop("checked")) {
            $(".interval").show()
        } else {
            $(".interval").hide();
        }
    });

    $("#isPcKey").change(function () {
        if ($(this).prop("checked")) {
            $("#keyboard").show()
        } else {
            $("#keyboard").hide()
        }
    });


    setTimeout(function () {
        highlightPianoKeysForScale(Object.keys(scales)[0]);
    }, 100);

    // 添加歌曲名字
    $('#song-name').text(songName);

    // 添加歌词
    let lyricElement = $('#lyrics');
    for (let i = 0; i < songData.length; i++) {
        const line = songData[i];
        if (!line.newLine) {
            lyricElement.append('<br>');
        }
    }

    //倍倍倍高音: QHP (Quadruple High Pitch)
    // 倍倍高音：THP (Triple High Pitch)
    // 倍高音：DHP (Double High Pitch)
    // 高音：HP (High Pitch)
    // 中音: MP (Middle Pitch)
    // 低音：LP (Low Pitch)
    // 倍低音：DLP (Double Low Pitch)
    // 倍倍低音：TLP (Triple Low Pitch)
    //倍倍倍低音: QLP (Quadruple Low Pitch)
    const noteNames = [
        { name: '6', pitch: 'QHP' },
        { name: '升6降7', pitch: 'QHP' },
        { name: '7', pitch: 'QHP' },
        { name: '1', pitch: 'THP' },
        { name: '升1降2', pitch: 'THP' },
        { name: '2', pitch: 'THP' },
        { name: '升2降3', pitch: 'THP' },
        { name: '3', pitch: 'THP' },
        { name: '4', pitch: 'THP' },
        { name: '升4降5', pitch: 'THP' },
        { name: '5', pitch: 'THP' },
        { name: '升5降6', pitch: 'THP' },
        { name: '6', pitch: 'THP' },
        { name: '升6降7', pitch: 'THP' },
        { name: '7', pitch: 'THP' },
        { name: '1', pitch: 'DHP' },
        { name: '升1降2', pitch: 'DHP' },
        { name: '2', pitch: 'DHP' },
        { name: '升2降3', pitch: 'DHP' },
        { name: '3', pitch: 'DHP' },
        { name: '4', pitch: 'DHP' },
        { name: '升4降5', pitch: 'DHP' },
        { name: '5', pitch: 'DHP' },
        { name: '升5降6', pitch: 'DHP' },
        { name: '6', pitch: 'DHP' },
        { name: '升6降7', pitch: 'DHP' },
        { name: '7', pitch: 'DHP' },
        { name: '1', pitch: 'HP' },
        { name: '升1降2', pitch: 'HP' },
        { name: '2', pitch: 'HP' },
        { name: '升2降3', pitch: 'HP' },
        { name: '3', pitch: 'HP' },
        { name: '4', pitch: 'HP' },
        { name: '升4降5', pitch: 'HP' },
        { name: '5', pitch: 'HP' },
        { name: '升5降6', pitch: 'HP' },
        { name: '6', pitch: 'HP' },
        { name: '升6降7', pitch: 'HP' },
        { name: '7', pitch: 'HP' },
        { name: '1', pitch: 'MP' },
        { name: '升1降2', pitch: 'MP' },
        { name: '2', pitch: 'MP' },
        { name: '升2降3', pitch: 'MP' },
        { name: '3', pitch: 'MP' },
        { name: '4', pitch: 'MP' },
        { name: '升4降5', pitch: 'MP' },
        { name: '5', pitch: 'MP' },
        { name: '升5降6', pitch: 'MP' },
        { name: '6', pitch: 'MP' },
        { name: '升6降7', pitch: 'MP' },
        { name: '7', pitch: 'MP' },
        { name: '1', pitch: 'LP' },
        { name: '升1降2', pitch: 'LP' },
        { name: '2', pitch: 'LP' },
        { name: '升2降3', pitch: 'LP' },
        { name: '3', pitch: 'LP' },
        { name: '4', pitch: 'LP' },
        { name: '升4降5', pitch: 'LP' },
        { name: '5', pitch: 'LP' },
        { name: '升5降6', pitch: 'LP' },
        { name: '6', pitch: 'LP' },
        { name: '升6降7', pitch: 'LP' },
        { name: '7', pitch: 'LP' },
        { name: '1', pitch: 'DLP' },
        { name: '升1降2', pitch: 'DLP' },
        { name: '2', pitch: 'DLP' },
        { name: '升2降3', pitch: 'DLP' },
        { name: '3', pitch: 'DLP' },
        { name: '4', pitch: 'DLP' },
        { name: '升4降5', pitch: 'DLP' },
        { name: '5', pitch: 'DLP' },
        { name: '升5降6', pitch: 'DLP' },
        { name: '6', pitch: 'DLP' },
        { name: '升6降7', pitch: 'DLP' },
        { name: '7', pitch: 'DLP' },
        { name: '1', pitch: 'TLP' },
        { name: '升1降2', pitch: 'TLP' },
        { name: '2', pitch: 'TLP' },
        { name: '升2降3', pitch: 'TLP' },
        { name: '3', pitch: 'TLP' },
        { name: '4', pitch: 'TLP' },
        { name: '升4降5', pitch: 'TLP' },
        { name: '5', pitch: 'TLP' },
        { name: '升5降6', pitch: 'TLP' },
        { name: '6', pitch: 'TLP' },
        { name: '升6降7', pitch: 'TLP' },
        { name: '7', pitch: 'TLP' },
        { name: '1', pitch: 'QLP' },
    ];


    const pianoElement = $('.piano');
    const pcPianoElement = $('.keyboard-map');

    var keysInGroup = [3, 12, 12, 12, 12, 12, 12, 12, 1]; // 每组的键数
    var totalKeys = keysInGroup.reduce((acc, cur) => acc + cur, 0); // 总键数
    var totalGroups = keysInGroup.length; // 总组数

    // 设置每个组的固定宽度比例
    var groupWidths = ['3.75%', '13.35%', '13.35%', '13.35%', '13.35%', '13.35%', '13.35%', '13.35%', '1.95%'];

    for (var i = 0; i < totalGroups; i++) {
        var $group = $("<li>").addClass("group").appendTo(".piano-group");
        $group.css("width", groupWidths[i]);
        if (keysInGroup[i] === 1) {
            $group.text(i + 1 + '组');
        } else {
            $group.text(i + 1 + '组');
        }
    }


    pianoKeys.forEach((note, index) => {
        const keyElement = $('<div></div>').addClass('piano-key').attr("id", note).attr("data-id", note)

        const pcKey = $('<div>-</div>').addClass('pc-key-item')
        if (note.includes('#') || note.includes('b')) {
            keyElement.addClass('black');
        }

        pianoElement.append(keyElement);
        pcPianoElement.append(pcKey);


        if (noteNames[index]) {
            const noteObject = noteNames[index];
            const noteName = noteObject.name;
            const pitch = noteObject.pitch;
            if (note.includes('#') || note.includes('b')) {
                //黑键
                $(".piano-key:eq(" + index + ")").html('<span>' + noteName + '</span>');
                $(".pc-key-item:eq(" + index + ")").css('width', '0.9%').css('background-color', '#444').css('color', '#fff');
            } else {
                //白键
                if (currentScale == 'C 调') {
                    if (index == 39) {
                        $(`#${note}`).html('<span class=' + pitch + '>' + noteName + '</span>');
                        $(`#${note}`).addClass('zzz');

                    } else {
                        $(`#${note}`).html('<span class=' + pitch + '>' + noteName + '</span>');
                    }
                }

            }

        }
    });


    var mergedKeys = [];
    mergedKeys = mergedKeys.concat(functionKeys, mainKeyboard, numpad);
    // console.log(mergedKeys)
    mergedKeys.forEach((item, idx) => {
        if (item.pianoKey) {
            $(".pc-key-item:eq(" + item.pianoKey + ")").html('<span>' + item.key + '</span>');
        }
    })




    /**
     * 高亮钢琴键
     *
     * @param chordName 和弦名
     */
    function highlightPianoKeys(chordName,mode) {
       
        // 在这里编写代码来解析和弦名，确定需要高亮的钢琴键
        $(".piano-key").removeClass("highlighted");
        let keysToHighlight1 = chords[chordName];
        if(mode>0){
            let transposedChord = [];
            for (let note of keysToHighlight1) {
                const index = pianoKeys.indexOf(note);
                if (index !== -1) {
                    let transposedIndex = index + mode;
                    if (transposedIndex < 0) {
                        transposedIndex += pianoKeys.length;
                    } else if (transposedIndex >= pianoKeys.length) {
                        transposedIndex -= pianoKeys.length;
                    }
                    transposedChord.push(pianoKeys[transposedIndex]);
                } else {
                    transposedChord.push(null);
                }
            }
            keysToHighlight1 = transposedChord
        }
        // 高亮显示对应的钢琴键
        $(".piano-key").removeClass('highlighted')
        keysToHighlight1.forEach((key, index) => {
            $(".piano-key[data-id='" + key + "']").addClass('highlighted')
        });
    }

    // highlightPianoKeys('C')


    /**
     * 高亮显示钢琴键盘上指定调式的音符键
     *
     * @param scaleName 调式名称，例如 'C 调'、'D 调' 等
     */
    function highlightPianoKeysForScale(scaleName) {
        $(".piano-key").removeClass("highlighted");

        // 获取对应调式的钢琴键数组
        const keysToHighlight = scales[scaleName];

        // 高亮显示对应的钢琴键
        keysToHighlight.forEach((key) => {
            //用key来匹配pianoKeys数组第几个，才是index
            var index = $.inArray(key, pianoKeys);
            if (key.includes('#') || key.includes('b')) {
                $(".piano-key:eq(" + index + ")").addClass('highlighted');
            } else {
                $(`#${key}`).addClass('highlighted');
            }
        });
    }

    /**
  * 生成歌曲歌词
  *
  * @param songData 歌曲数据，包含和弦与歌词的数组
  */
    function generateSongLyrics(songData) {
        $(".lyrics-title").text(songName);
        const lyricsContainer = $(".lyrics-content");
        lyricsContainer.empty();

        // 循环遍历数据并添加到页面中
        songData.forEach(function (line) {
            if (line.newLine) {
                const lineHtml = `<div class="line song-line"><p><span class="chord selectKey">${line.chord}</span></p><p>${line.lyrics}</p></div>`;
                lyricsContainer.append(lineHtml);
            } else {
                const lineHtml = `<br/><div class="line song-line"><p><span class="chord selectKey">${line.chord}</span> ${line.lyrics}</p></div>`;
                lyricsContainer.append(lineHtml);
            }
        });
    }

    generateSongLyrics(songData)


    $(".piano-key").on("click touchstart", function () {
        var index = $(this).index();
        if (!isCompute) {
            //获取index
            // console.log("点击钢琴键盘的index:" + index)
            //获取id
            var id = $(this).attr("id");
            var audio = $('#piano-audio')[0];
            audio.src = domain + "/mp3/" + index + ".mp3";
            audio.currentTime = 0;
            audio.play();
        } else {
            //计算模式
            if ($(".interval-sound").length < 8) {
                $(this).addClass('highlighted')
                $(".interval-tips").hide()
                let name = pianoKeys[index]
                if (intervalList.includes(name)) {
                    intervalList = intervalList.filter(item => item !== name); // 使用filter来删除重复项
                    $(".piano-key").eq(index).removeClass('highlighted')
                } else {
                    intervalList.push(name)
                }
                //把name用字符串分割
                updateIntervalList(intervalList)
            } else {
                $.fn.msg({
                    content: '长度不要超过8个音符',
                    type: 'error'
                });
            }
        }
    })

    function updateIntervalList(keys) {
        $(".interval-list").html('');
        keys.sort((a, b) => pianoKeys.indexOf(a) - pianoKeys.indexOf(b));
        keys.forEach((key, index) => {
            let nameArr;
            if (key.includes('#') || key.includes('b')) {
                let nameArr = key.split("/");
                nameArr = nameArr[0].split("");
                $(".interval-list").append("<div class='interval-sound' data-key='" + key + "'>" + nameArr[1] + nameArr[0] + "<small>" + nameArr[2] + "</small>" + "</div>");
            } else {
                nameArr = key.split("");
                $(".interval-list").append("<div class='interval-sound' data-key='" + key + "'>" + nameArr[0] + "<small>" + nameArr[1] + "</small>" + "</div>");
            }
            if (index > 0) {
                let result = pianoKeys.indexOf(keys[index]) - pianoKeys.indexOf(keys[index - 1]);
                if (typeof intervals[result] == 'undefined') {
                    $.fn.msg({
                        content: '不要乱点跨度太大了!',
                        type: 'error'
                    })
                    $(".interval-sound").eq(index).remove();
                } else {
                    $(".interval-sound").eq(index).before("<div class='interval-name'>" + intervals[result] + "</div>");
                }
            }
        });
    }


    $(document).on('click', ".selectKey", function () {
        var selectedIndex = $('#select-tuning option:selected').index(); //调
        let val = $(this).text()
        highlightPianoKeys(val,selectedIndex);
    })


    $(document).keydown(function (e) {
        var activeElement = $(document.activeElement);
        if (activeElement.is('input') || activeElement.is('textarea')) {
            return; // 如果焦点在input或textarea上，则不执行后续操作
        }
        var key = e.which;
        var keyIndex = findPianoKeyByCode(key)
        playTrack(keyIndex, key);
    })

    // 监听键盘抬起事件
    $(document).keyup(function (event) {
        stopAllTracks();
    });

    // 播放音轨
    function playTrack(index, key) {
        if (!audioMap[index]) {
            var audioSrc = index + ".mp3";
            var { audio, track } = createTrack(audioSrc);
            var merger = audioContext.createChannelMerger(2);
            track.connect(merger);
            merger.connect(audioContext.destination);
            audio.play();
            audioMap[index] = { audio: audio, playing: true }; // 记录音轨的播放状态
            // 添加高亮效果
            highlightDiv(index, key);
        }
    }

    // 高亮div
    function highlightDiv(index, key) {
        $(".piano-key").eq(index).addClass('active')
        $(".key[data-code=" + key + "]").addClass("active")
        $(".pc-key-item:eq(" + index + ")").addClass("tantiao")
        activeDivs.push(index);
    }

    // 取消高亮div
    function unhighlightDiv(index, key) {
        $(".piano-key").eq(index).removeClass('active')
        $(".key").removeClass("active")
        $(".pc-key-item").removeClass("tantiao")
        activeDivs = activeDivs.filter(item => item !== index);
    }

    // 停止音轨
    function stopAllTracks() {
        Object.values(audioMap).forEach(function (item) {
            var audio = item.audio;
            var playing = item.playing;
            if (playing) {
                // 等待当前音轨播放完毕后再停止
                audio.addEventListener('ended', function () {
                    audio.pause();
                    audio.currentTime = 0;
                }, { once: true });
            } else {
                audio.pause();
                audio.currentTime = 0;
            }
        });
        audioMap = {};
        // 移除所有高亮效果
        activeDivs.forEach(function (index) {
            unhighlightDiv(index);
        });
        activeDivs = [];
    }

    // 创建音轨
    function createTrack(src) {
        var audio = new Audio(domain + "/mp3/" + src);
        var track = audioContext.createMediaElementSource(audio);
        return { audio: audio, track: track };
    }

    function mergeKeyArrays() {
        var mergedKeys = [];
        mergedKeys = mergedKeys.concat(functionKeys, mainKeyboard, numpad);
        return mergedKeys;
    }

    function findPianoKeyByCode(num) {
        var mergedKeys = mergeKeyArrays();
        for (var i = 0; i < mergedKeys.length; i++) {
            if (mergedKeys[i].code === num.toString()) {
                return mergedKeys[i].pianoKey;
            }
        }
        return null; // 如果未找到对应的code，则返回null
    }

    function findPianoKeyByKey(index) {
        if (index) {
            var mergedKeys = mergeKeyArrays();
            for (var i = 0; i < mergedKeys.length; i++) {
                if (mergedKeys[i].pianoKey === index.toString()) {
                    return mergedKeys[i].code;
                }
            }
            return null; // 如果未找到对应的code，则返回null
        }
    }

    // { key: "S", code: "83", pianoKey: '41' }



    // 生成功能区域键
    functionKeys.forEach(function (key) {
        $('#keyboard .function-keys').append('<div class="key " data-code=' + key.code + '>' + key.key + '</div>');
    });

    // 生成主键盘区键
    mainKeyboard.forEach(function (key) {
        if (key.colspan2) {
            $('#keyboard .main-keyboard').append('<div class="key colspan2" data-code=' + key.code + '>' + key.key + '</div>');
        } else if (key.colspan9) {
            $('#keyboard .main-keyboard').append('<div class="key colspan9" data-code=' + key.code + '>' + key.key + '</div>');
        } else {
            $('#keyboard .main-keyboard').append('<div class="key" data-code=' + key.code + '>' + key.key + '</div>');
        }
    });

    // 生成小键盘区键
    numpad.forEach(function (key) {
        if (key.rowspan2) {
            $('#keyboard .numpad').append('<div class="key rowspan2" data-code=' + key.code + '>' + key.key + '</div>');
        } else {
            $('#keyboard .numpad').append('<div class="key" data-code=' + key.code + '>' + key.key + '</div>');
        }
    });

    var midiAccess = null; // 保存 MIDI 访问对象
    var lastProcessedTime = 0; // 上次处理逻辑的时间戳

    $(document).ready(function () {
        $('.switch-input').change(function () {
            if ($(this).is(':checked')) {
                // 开关打开状态
                if (navigator.requestMIDIAccess) {
                    navigator.requestMIDIAccess().then(onMIDISuccess).catch(function(error) {
                        // 处理错误
                        console.error("无法访问MIDI设备:", error);
                    });
                } else {
                    $.fn.msg({
                        content: '浏览器不支持MIDI!',
                        type: 'error'
                    })
                    $("#switch").prop("checked", false);
                    $(".switch-box .switch-label::before").css('transform', 'translateX(0px)')
                    $(".switch-box .switch-label").attr('background', '')
                }
            } else {
                // 开关关闭状态
                $.fn.msg({
                    content: '断开连接',
                    type: "error"
                })
                disconnectMIDI()
                // console.log('开关已关闭');
                $(".mini-name").html('');
            }
        });
    });

    function onMIDISuccess(midiAccess) {
        console.log('MIDI ready!');
        midiAccess = midiAccess; // 保存 MIDI 访问对象
        var inputs = midiAccess.inputs;

        // 选择你要连接的 MIDI 键盘
        if (midiAccess.inputs.size > 0) {
            $.fn.msg({
                content: '连接成功!',
                type: "success"
            })
            inputs.forEach(function (input) {
                $(".mini-name").html('<span class="state"></span>' + "设备名称：" + input.name)
                input.onmidimessage = getMIDIMessage;
            });
        } else {
            $.fn.msg({
                content: '未找到MIDI设备!',
                type: "error"
            })
            $("#switch").prop("checked", false);
            $(".switch-box .switch-label::before").css('transform', 'translateX(0px)')
            $(".switch-box .switch-label").attr('background', '')
        }

        // 添加设备状态变化的监听器
        midiAccess.onstatechange = function (event) {
            // 获取设备状态变化后的设备列表
            var inputs = midiAccess.inputs.values();
            var inputsArray = [];
            for (var input = inputs.next(); input && !input.done; input = inputs.next()) {
                inputsArray.push(input.value);
            }

            // 如果设备列表为空，则说明所有设备都已关闭
            if (inputsArray.length === 0) {
                $.fn.msg({
                    content: 'MIDI设备已关闭!',
                    type: "error"
                })
                $(".mini-name").html('');
                $("#switch").prop("checked", false);
                $(".switch-box .switch-label::before").css('transform', 'translateX(0px)')
                $(".switch-box .switch-label").attr('background', '')
            }
        };

    }

    function onMIDIFailure(error) {
        $.fn.msg({
            content: '连接失败!',
            type: 'error'
        })
        $("#switch").prop("checked", false);
        $(".switch-box .switch-label::before").css('transform', 'translateX(0px)')
        $(".switch-box .switch-label").attr('background', '')
    }

    function getMIDIMessage(event) {
        var currentTime = Date.now();
        // 计算当前时间和上次处理时间之间的差值
        var timeDiff = currentTime - lastProcessedTime;

        var command = event.data[0];
        var index = event.data[1];
        var velocity = (event.data.length > 2) ? event.data[2] : 0;
        let key = findPianoKeyByKey(index - 21);
        switch (command) {
            case 144: // Note On
                if (velocity !== 0) {
                    // 按键按下时的操作
                    // console.log(index-21);
                    highlightDiv(index - 21, key)
                }
                break;
            case 248: // Note Off
                // 按键抬起时的操作
                if (timeDiff >= 1000) {
                    activeDivs.forEach(function (index) {
                        unhighlightDiv(index);
                    });
                    lastProcessedTime = currentTime;
                }
                break;
            // 更新上次处理时间

        }

    }

    function disconnectMIDI() {
        if (midiAccess) {
            // 关闭 MIDI 连接
            midiAccess.inputs.forEach(function (input) {
                input.onmidimessage = null; // 移除 MIDI 事件监听器
            });
            console.log("MIDI disconnected.");
        } else {
            console.warn("MIDI not connected.");
        }
    }


});
